package com.qilin.hscs.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qilin.hscs.enums.UserHostUsingStatus;
import com.qilin.hscs.enums.UserRoleEnum;
import com.qilin.hscs.pojo.User;
import com.qilin.hscs.repository.UserHostRepository;
import com.qilin.hscs.service.UserService;
import com.qilin.hscs.util.IsUserCanDo;
import com.qilin.hscs.util.TokenUtil;
import com.qilin.hscs.vo.UserHostVO;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by 10188 on 2018/5/7.
 */
@Aspect
@Component
@Order(2)
public class AuthorizationAspect {

    private static final Logger logger= LogManager.getLogger(AuthorizationAspect.class.getName());

    @Autowired
    private UserHostRepository repository;

    @Autowired
    private UserService userService;

    @Pointcut("within(com.qilin.hscs.controller.HostController) || within(com.qilin.hscs.controller.UserHostController)")
    public void RoleController() {}

    @Before("RoleController()")
    public void doBefore(JoinPoint joinPoint) {
       logger.info("do authorization");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String authentication = request.getHeader("authentication");
        String token = authentication.substring(6);
        Claims claims = TokenUtil.parse(token);
        String subject=claims.getSubject();
        logger.debug("subject={}",subject);
        JSONObject subjectObj = JSON.parseObject(subject);
        String username = subjectObj.getString("username");
        User user = userService.findOneByPhone(username);
        List<UserHostVO> userhosts = repository.findHostByUserId(user.getId());
        Integer role=null;
        for (UserHostVO userhost : userhosts) {
            if (userhost.getIsUse() == UserHostUsingStatus.ONLINE.getCode()) {
                role = userhost.getRole();
            }
        }
        String operationName = joinPoint.getSignature().getName();
        logger.debug("operationName={}",operationName);
        IsUserCanDo.judge(role, operationName);
    }
}
